import Vue from "vue";
import VueRouter from "vue-router";
import MyImportant from '../views/MyImportant.vue'
import MyHome from '../views/MyHome.vue'
import MyUser from '../views/MyUser.vue'
import MyMall from '../views/MyMall.vue'
import PageOne from '../views/PageOne.vue'
import PageTwo from '../views/PageTwo.vue'
import MyLogin from  '../views/MyLogin.vue'
import Cookie  from 'js-cookie'
Vue.use(VueRouter);

//1.创建路由组件(引入)
//2.将路由与组件进行映射
const routes = [
    //主路由
    {
        path: '/',
        component: MyImportant,
        redirect: 'home',
        children:[
            //子路由
            { path: 'home',  name: 'home',component: MyHome }, //主页
            { path: 'user',  name: 'user', component: MyUser }, //用户管理
            { path: 'mall',  name: 'mall',component: MyMall }, //商品管理
            { path: 'page1', name: 'page1',component: PageOne },
            { path: 'page2', name: 'page2',component: PageTwo },
        ]
        
    },
    {
        path:'/login',
        name:'login',
        component: MyLogin
    }
    
    
]
//3.创建router实例
const router = new VueRouter({
    routes
})
router.beforeEach( (to,from ,next)=> {
    //判断路由存不存在
    const token = Cookie.get('token')
    if(!token && to.name!=='login'){// token不存在，说明当前用户是未登录，应该跳转至登录页
        next({
            name:'login',
        })
    }else if(token && to.name!== 'login'){// token存在，说明用户登录，此时跳转至首页
        next({
            name:'home',
        })
    }else{
        next()
    }
})

export default router
//4.挂载到根实例

